import { addRoleApi, editRoleApi } from "@/api/managementCenter/roleAndPermission";
import FormHook from "@/hook/formHook";
import { message } from "ant-design-vue";
export default function OperationHook(state: Base.GeneraDataType) {
  const { passData, formState, formDataRef, emit, clientOpts, type } = state;
  const { resetFields } = FormHook({ formState });
  const submitHandle = () => {
    formDataRef.value.validate().then(() => {
      const hasPermissionPanle = clientOpts.value.filter((t: any) => t.checked);
      if (!hasPermissionPanle.length) return message.error("至少拥有一个模块权限!");
      const clients: Array<RoleAndPermission.Clients> = [];
      for (let i = 0; i < hasPermissionPanle.length; i++) {
        const { code, name } = hasPermissionPanle[i];
        clients.push({
          code,
          name,
          child: hasPermissionPanle[i].clients
          // child: convertToTree(cloneDeep(hasPermissionPanle[i].clients), "id", "pid")
        });
      }
      const { name, remark } = formState;
      const params: RoleAndPermission.AddForm = {
        name,
        remark,
        clients
      };
      let requestFn;
      if (type.value === 1) {
        requestFn = addRoleApi;
        Reflect.deleteProperty(params, "id");
      } else {
        requestFn = editRoleApi;
        params.id = passData.value.id;
      }
      requestFn(params).then((res: any) => {
        const { code } = res;
        if (code === 200) {
          message.success("操作成功!");
          emit("submit");
        }
      });
    });
  };
  const cancelHandle = () => {
    resetFields();
    formDataRef.value.clearValidate();
    emit("update:visible", false);
  };
  return {
    submitHandle,
    cancelHandle,
    resetFields
  };
}
